<?php

namespace App\Http\Controllers;

use App\Models\CollArea;
use App\Models\CollPosition;
use App\Models\DeviceInfo;
use App\Models\ProductCategory;
use App\Models\SweetnessList;
use App\Models\WebConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Agreement;

class CommonController extends Controller
{
    protected static $baseImgUrl = 'https://winesh.oss-cn-beijing.aliyuncs.com';


    public function getSweetnessList()
    {
        $lists = SweetnessList::select('id','name')
            ->get();

        return response()->json(['status' => 1, 'data' => $lists]);
    }

    public function getAllArea()
    {
        $provinceArray = [];
        $province = CollArea::where('grade', 1)->orderBy('id', 'asc')->get();

        foreach ($province as $key => $value) {
            $area = CollArea::where('grade', 2)->where('pid', $value['cid'])->orderBy('id', 'asc')->get();
            $areaArray = [];
            foreach ($area as $k => $v) {
                $city = CollArea::where('grade', 3)->where('pid', $v['cid'])->orderBy('id', 'asc')->get();
                $cityArray = [];
                if (count($city) == 0) {
                    $cityArray[] = [
                        'id' => 0,
                        'name' => '',
                        'pid' => $v['cid'],
                        'level' => 3
                    ];
                } else {
                    foreach ($city as $city_k => $city_v) {
                        $cityArray[] = [
                            'id' => $city_v['cid'],
                            'name' => $city_v['name'],
                            'pid' => $city_v['pid'],
                            'level' => $city_v['grade']
                        ];
                    }
                }

                $areaArray[] = [
                    'id' => $v['cid'],
                    'name' => $v['name'],
                    'pid' => $v['pid'],
                    'level' => $v['grade'],
                    'children' => $cityArray
                ];
            }
            $provinceArray[] = [
                'id' => $value['cid'],
                'name' => $value['name'],
                'pid' => 10000,
                'level' => $value['grade'],
                'children' => $areaArray
            ];
        }

        return response()->json(['status' => 1, 'data' => $provinceArray]);
    }

    /**
     * 商城首页获取分类快捷方式
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCates(Request $request)
    {
        $is_shortcut = $request->is_shortcut;
        if ($is_shortcut == 1) {
            $cates = ProductCategory::select('id', 'name', 'icon')->where('is_shortcut', 1)->where('status', 1)->orderBy('sort', 'asc')->get();
        } else {
            $cates = ProductCategory::select('id', 'name', 'icon')->where('status', 1)->orderBy('sort', 'asc')->get();
        }

        if ($cates) {
            foreach ($cates as $v) {
                $v->icon = $v->icon ? self::$baseImgUrl . '/' . $v->icon : '';
            }
        }

        return response()->json(['status' => 1, 'data' => $cates]);
    }

    public function getPosByPid(Request $request)
    {
        $pid = $request->pid;
        if (!$pid) {
            $pid = 0;
        }
        $positions = CollPosition::where('pid', $pid)->select('cid', 'pid', 'name')->orderBy('id', 'asc')->get();
        if ($positions) {
            foreach ($positions as $v) {
                $v->id = $v->cid;
            }
        }
        return response()->json(['status' => 1, 'data' => $positions]);
    }

    public function getSoftVersion()
    {
        $newVersion = WebConfig::getConfig('appVersionName');
        return response()->json(['status' => 1, 'data' => $newVersion]);
    }

    function money_change($type, $fuid, $tuid, $money, $relationId, $op = null)
    {
        $data['uid'] = $fuid;
        $data['targetuid'] = $tuid;
        $data['relation_id'] = $relationId;

        $data['recordtype'] = $type['recordtype'];
        $data['moneytype'] = $type['moneytype'];
        $data['changetype'] = $type['changetype'];

        $data['money'] = $money['money'];
        $data['hasmoney'] = $money['hasmoney'];
        if (isset($money['fee_money'])) {
            $data['fee_money'] = $money['fee_money'];
        }

        if (!empty($op)) {
            $data['op'] = $op;
        }
        $data['createtime'] = time();
        $result = DB::table('money_change')->insert($data);
        return $result;
    }

    public function getCityByTX(Request $request)
    {
        $lat = $request->lat;
        $lng = $request->lng;
        if (!$lat || !$lng) {
            return response()->json(['status' => 0, 'msg' => '无法定位到所在城市！']);
        }

        $place = new PlaceController();
        $res = $place->getLocationTX($lat, $lng);

        return response()->json(['status' => 1, 'data' => $res]);
    }

    /**
     * 获取微信公众号openId
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getWxOpenId(Request $request)
    {
        $code = $request->code;
        if (!$code) {
            return response()->json(['status' => 0, 'msg' => '关键参数缺失！']);
        }
        $wechat = new WechatController();

        $data1 = $wechat->get_access_token($code);
        $openId = $data1['openid'];
        $data2 = $wechat->get_token();
        $accessToken = $data2['access_token'];

        $info = $wechat->get_user_info($accessToken, $openId);
        $unionId = $info["unionid"];
        $wxInfo = DB::table('weixin_info')->where('unionid', $unionId)->first();
        if ($wxInfo && !$wxInfo->openid2) {
            //补全公众号信息
            DB::table('weixin_info')->where('id', $wxInfo->id)->update(['openid2' => $openId]);
        }
        return response()->json(['status' => 1, 'data' => $info]);
    }

    /**
     * 获取小程序openid
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAppletOpenId(Request $request)
    {
        $code = $request->code;
        if (!$code) {
            return response()->json(['status' => 0, 'msg' => '关键参数缺失！']);
        }
        $wechat = new WechatController();
        $data = $wechat->get_open_id_wechat($code);

        return response()->json(['status' => 1, 'data' => $data['openid']]);
    }

    /**
     * 获取微信信息
     */
    public function getWxInfo(Request $request)
    {
        $url = $request->url;
        $wechat = new WechatController();
        $time = time();
        $res = $wechat->share($time, $url);
        return $res;
    }

    /**
     * 添加设备
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addDevice(Request $request)
    {
        $clientId = $request->client_id;
        $dInfo = DeviceInfo::where('device_id', $clientId)->first();
        if ($dInfo) {
            return response()->json(['status' => 1, 'msg' => '该设备已注册']);
        }

        DeviceInfo::create(['device_id' => $clientId]);
        return response()->json(['status' => 1, 'msg' => '该设备注册成功']);
    }

    function create_order($uid = 0, $type = 1)
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $uCode = array('K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T');
        $len = count($yCode);
        $yu = $uid % $len;
        $ye = (intval(date('Y')) - 2014) % $len;
        $orderSn = $yCode[$ye] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%04d%02d', rand(1000, 9999), rand(0, 99)) . $uCode[$yu] . $type;
        return $orderSn;
    }

    /**
     * 获取协议详情
     * @param Request $request
     * @return mixed
     */
    public function getAgreement(Request $request)
    {
        $type = $request->type;
        if (!$type) {
            $type = 'privacy-policy';
        }
        $row = Agreement::where('type', $type)->first();
        return response()->json(['status' => 1, 'data' => $row]);
    }
}
